<template>
  <div class="page">
    <global-header title="二次验证" @back="$router.back()" />
    <main class="page-main mx-[15px] mt-[15px] text-[14px]">
      <ul class="bg-[#fff] px-[15px] py-[20px] rounded-[10px]" v-if="state.isSetting == 0">
        <li>
          <div class="text-[15px] font-bold">步骤：</div>
          <div class="mt-[10px]">
            <p>1.下载安装“身份验证器” （Authenticator）客户端。</p>
            <p>2.身份验证器下载地址：</p>
            <p class="break-all">
              <span>iPhone用户下载地址（中国大陆）：</span>
              <a class="text-blue" href="https://itunes.apple.com/app/id1573732533" target="_blank">
                点击下载
              </a>
            </p>
            <p class="break-all">
              <span>iPhone用户下载地址（海外）：</span>
              <a class="text-blue" href="https://itunes.apple.com/app/id388497605" target="_blank">
                点击下载
              </a>
            </p>
            <p class="break-all">
              <span>安卓&鸿蒙用户下载地址：</span>
              <a
                class="text-blue"
                href="https://download3.runtietz.com/download/tools/com.tencent.authenticator_1.0.apk"
                target="_blank"
              >
                点击下载
              </a>
            </p>
            <p class="break-all">
              3.使用验证器“扫码二维码”功能扫描以下二维码，再输入验证器上的6位验证码，完成认证。
            </p>
          </div>
          <div class="flex flex-col justify-center items-center mt-[6px]">
            <div class="w-[200px] h-[200px] bg-[#999]">
              <img v-if="state.base64Img" class="w-[200px] h-[200px]" :src="state.base64Img" />
            </div>
            <div class="mt-[5px]">
              {{ form.Secret }}
            </div>
          </div>
        </li>
        <li class="mt-[15px]">
          <div class="text-[15px] font-bold">二次验证码：</div>
          <div class="mt-[10px]">
            <van-field
              class="!bg-[#f6f9fe] !rounded-[6px]"
              v-model="form.Code"
              type="text"
              placeholder="请输入谷歌验证码"
            />
          </div>
        </li>
      </ul>
      <ul class="bg-[#fff] px-[15px] py-[20px] rounded-[10px]" v-else>
        <li>
          <div class="text-[15px] font-bold">二次认证：</div>
          <div class="my-[10px] text-red">已绑定</div>
        </li>
      </ul>
      <div class="mt-[15px]">
        <van-button block type="primary" @click="confirm" v-if="state.isSetting == 0">
          确认提交
        </van-button>
        <van-button block type="primary" @click="handleReset" v-else>重置</van-button>
      </div>
    </main>
  </div>
</template>
<route>
  {
    name: "admin-main-authenticator",
    meta: {
      pageIndex: 4,
    }
  }
</route>
<script setup lang="ts">
import { debounce } from "lodash-es";
import { reqGoogleSecret, reqGoogleSecretBind, reqGoogleSecretReset } from "@/api/main";
import { toast } from "@/utils/toast";

const emit = defineEmits(["update"]);

const state = reactive({
  loading: false,
  updating: false,
  base64Img: "",
  isSetting: 0
});
const form = reactive({
  Secret: "",
  Code: ""
});

const setBase64Img = (str: string) => {
  return `data:image/png;base64,${str}`; // 修改 mime 类型以适应图片格式
};

const getData = async () => {
  const loading = toast.loading("加载中...");
  try {
    const res = await reqGoogleSecret();
    form.Secret = res.data.Secret;
    state.base64Img = setBase64Img(res.data.QrCode);
    state.isSetting = res.data.IsSetting;
    loading.close();
  } catch (error) {
    loading.close();
    console.log(error);
  }
};

// 重置谷歌验证器
const handleReset = () => {
  showConfirmDialog({
    message: "是否重置谷歌验证器？",
    className: "confirm-dialog",
    beforeClose: async (action: string) => {
      return new Promise<boolean>(async resolve => {
        if (action === "confirm") {
          // on confirm
          try {
            await reqGoogleSecretReset({
              Id: null
            });
            toast.success("重置成功");
            resolve(true);
          } catch (error) {
            resolve(true);
          }
        } else {
          resolve(true);
        }
      });
    }
  });
};

const confirm = debounce(
  async () => {
    if (!form.Code) {
      toast.info("请输入谷歌验证码");
      return false;
    }
    state.updating = true;
    try {
      await reqGoogleSecretBind({
        ...form
      });
      state.updating = false;
      toast.success("绑定成功");
      getData();
    } catch (error) {
      state.updating = false;
      console.log(error);
    }
  },
  500,
  { leading: true, trailing: false }
);

onMounted(() => {
  getData();
});
</script>
